package dev.alm.reggietakeoutservice.controller;

import com.alibaba.druid.util.StringUtils;
import dev.alm.reggietakeoutservice.common.Result;
import dev.alm.reggietakeoutservice.dto.UserPageQuery;
import dev.alm.reggietakeoutservice.entity.User;
import dev.alm.reggietakeoutservice.service.JedisService;
import dev.alm.reggietakeoutservice.service.UserService;
import dev.alm.reggietakeoutservice.utils.JwtUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private JedisService jedisService;

    @PostMapping("add")
    public Result addUser(@RequestBody User user) {
        User user1 = userService.addUser(user);
        if (user1 == null) {
            return Result.fail(50000, "添加失败");
        } else {
            return Result.success(user1);
        }
    }

    @PostMapping("getUserById")
    public Result getUserById(@RequestBody User user) {
        User userById = userService.getUserById(user.getId());
        if (userById == null) {
            return Result.fail(50000, "查询失败");
        } else {
            return Result.success(userById);
        }
    }

    @PostMapping("login")
    public Result login(@RequestBody User user) {
        Boolean login = userService.login(user);

        if (!login) {
            return Result.fail(50000, "用户名或密码错误");
        }
        // 生成token
        String token = null;
        // 先查询redis中是否已有相应的记录
        String s = jedisService.get(user.getUsername());
        if (!StringUtils.isEmpty(s)) {
            token = s;
        } else {
            token = JwtUtil.createToken(user);
        }
        // TODO : 存入redis
        String set = jedisService.set(user.getUsername(), token);
        if (!set.equals("OK")) {
            return Result.fail(50000, "登录失败");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @PostMapping("info")
    public Result info(@Param("token") String token) {
        return null;
    }

    @PostMapping("getUserListByConditionAndPage")
    public Result getUserListByConditionAndPage(@RequestBody UserPageQuery userPageQuery) {
        Map<String, Object> list = userService.getUserListByConditionAndPage(userPageQuery);
        return Result.success(list);
    }

}